package concurrecy;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousCloseException;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

class NioTask implements Runnable {

    private SocketChannel channel;
    private String name;

    public NioTask(String name, SocketChannel channel) {
        this.name = name;
        this.channel = channel;
    }

    @Override
    public void run() {
        System.out.println("ready read " + name);
        try {
            channel.read(ByteBuffer.allocate(1));
        } catch (ClosedByInterruptException e) {
            System.out.println("ClosedByInterruptException " + name);
        } catch (AsynchronousCloseException e) {
            System.out.println("AsynchronousCloseException " + name);
        } catch (IOException e) {
            System.out.println("io exception " + name);
        }
        System.out.println("Exit " + name);
    }
}

public class TerminateNioTaskDemo {
    public static void main(String[] args) throws IOException, InterruptedException {
        ExecutorService service = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(8080);
        InetSocketAddress address = new InetSocketAddress("localhost", 8080);
        SocketChannel sc1 = SocketChannel.open(address);
        SocketChannel sc2 = SocketChannel.open(address);

        service.execute(new NioTask("Task1", sc1));
        Future<?> task2 = service.submit(new NioTask("Task2", sc2));

        TimeUnit.SECONDS.sleep(2);
        System.out.println("shutdown");
        service.shutdown();

        TimeUnit.SECONDS.sleep(2);
        System.out.println("sc1.close");
        sc1.close();

        TimeUnit.SECONDS.sleep(2);
        System.out.println("task2.cancel");
        task2.cancel(true);
    }
}
